package com.ljkj.cordial.chat.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.media.AudioManager;
import android.net.Uri;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.lanjiu.lib.imclient.user.UserPreferences;
import com.lanjiu.lib.utils.sp.SPKeys;
import com.lanjiu.lib.utils.sp.SharedPreferenceHelper;
import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.base.BaseActivity;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.dao.AlbumTableBean;
import com.ljkj.cordial.chat.dao.ChatTableBean;
import com.ljkj.cordial.chat.util.AlbumManageUtil;
import com.ljkj.cordial.chat.util.SpeechVoiceUtil;
import com.ljkj.cordial.chat.widget.CommonHintDialog;
import com.nic.view.util.AndroidFileUtil;

import java.io.File;
import java.text.DecimalFormat;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class FileDownloadActivity extends BaseActivity {

    @BindView(R.id.iv_file_type)
    ImageView ivFileType;
    @BindView(R.id.tv_fileName)
    TextView tvFileName;
    @BindView(R.id.tv_fileSize)
    TextView tvFileSize;
    @BindView(R.id.cp_file_progress)
    ContentLoadingProgressBar cpFileProgress;
    @BindView(R.id.tv_download)
    TextView tvDownload;
    @BindView(R.id.iv_success)
    ImageView ivSuccess;
    @BindView(R.id.tv_locPath)
    TextView tvLocPath;
    private Long chatId;
    private ChatTableBean msg;
    private String fileId;

    @Override
    public int getContentLayoutId() {
        return R.layout.activity_file_download;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        cpFileProgress.getIndeterminateDrawable().setColorFilter(ContextCompat.getColor(this, R.color.blue3), PorterDuff.Mode.MULTIPLY);
        cpFileProgress.hide();
        chatId = getIntent().getLongExtra(Canstants.KEY_INFO, 0L);
        if (chatId > 0L) {
            msg = ChatTableBean.getTableFromId(String.valueOf(chatId));
            ivFileType.setImageResource(getMineTypeByUrl(msg.getFileUrl()));
            tvFileName.setText(getFileName(msg.getFileUrl(), "\\"));
            tvFileSize.setText(getFileSize(msg.getFileLength()));
            init(msg);
        }
    }

    public static void jumpTo(Context context, Long id) {
        Intent intent = new Intent(context, FileDownloadActivity.class);
        intent.putExtra(Canstants.KEY_INFO, id);
        context.startActivity(intent);
    }

    private void init(ChatTableBean item) {
        if (item == null) {
            return;
        }
        if (!TextUtils.isEmpty(item.getAlbumId()) && Long.parseLong(item.getAlbumId()) > 0) {
            AlbumTableBean al = AlbumTableBean.queryById(Long.parseLong(item.getAlbumId()));
            if (al != null && !TextUtils.isEmpty(al.getMPath())) {
                tvDownload.setVisibility(View.GONE);
//                getToolbarRightIv().setVisibility(View.VISIBLE);
//                getToolbarRightIv().setImageResource(R.mipmap.icon_elli);
//                getToolbarRightIv().setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View vv) {
//
//                    }
//                });
                setItemClick(al.getMPath(), this);
            }
            cpFileProgress.hide();

        }
    }

    public void setItemClick(String path, Context context) {
        if (!TextUtils.isEmpty(path)) {
            int mineType = AlbumTableBean.getFileType(path);
            if (AlbumTableBean.TYPE_VIDEO == mineType) {
                Intent intent = AndroidFileUtil.openFile(path);
                if (intent != null) {
                    context.startActivity(intent);
                    SpeechVoiceUtil.setAudioMute(context, false);
                }
                finish();
            } else if (AlbumTableBean.TYPE_IMAGE == mineType) {
                AlbumManageUtil
                        .getInstance().lookLargePhoto(context, path);
            } else if (AlbumTableBean.TYPE_RECORD_FILE == mineType) {
                String key = SPKeys.Key.CONFIG_VOICE_PLAY_BY_MAC + UserPreferences.getUserId();
                boolean isMac = SharedPreferenceHelper.create(SPKeys.Name.CONFIG).getBoolean(key, Canstants.DEFAULT_MAC);
                AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
                if (am != null) {
                    am.setSpeakerphoneOn(!isMac);
                    am.setMode(isMac ? AudioManager.MODE_IN_CALL : AudioManager.MODE_NORMAL);
                }
                AlbumManageUtil.getInstance().playVoice(path, isMac, new AlbumManageUtil.OnPlayAnimListener() {
                    @Override
                    public void onStartAnim() {
                    }

                    @Override
                    public void onStopAnim() {
                    }
                });
            } else {
                Intent intent = AndroidFileUtil.openFile(path);
                if (intent != null) {
                    context.startActivity(intent);
                }
                finish();
            }
        }
    }

    private void showFile(ChatTableBean item) {
        if (cpFileProgress.isShown()) {
            return;
        }
        cpFileProgress.show();
        if (Canstants.SINGLE_CHAT == item.getFromType())
            AlbumManageUtil.getInstance().downLoadFileFriend(item.getFileUrl(), AlbumTableBean.TYPE_EXTRA_FILE, item.getTargetId(), new AlbumManageUtil.OnFileResponse() {
                @Override
                public void onProgress(int progress) {
                    super.onProgress(progress);
                    if (isFinishing()) {
                        return;
                    }
                    cpFileProgress.setProgress(progress);
                }

                @Override
                public void onResult(String path, String fileId) {
                    if (isFinishing()) {
                        return;
                    }
                    ivSuccess.setVisibility(View.VISIBLE);
                    resultFile(fileId, item);

                }
            });
        else
            AlbumManageUtil.getInstance().downLoadFileGroupMember(item.getFileUrl(), AlbumTableBean.TYPE_EXTRA_FILE
                    , item.getGroupType(), item.getGroupId(), item.getTargetType(), item.getTargetId(), new AlbumManageUtil.OnFileResponse() {
                        @Override
                        public void onProgress(int progress) {
                            super.onProgress(progress);
                            if (isFinishing()) {
                                return;
                            }
                            cpFileProgress.setProgress(progress);
                        }

                        @Override
                        public void onResult(String url, String fileId) {
                            if (isFinishing()) {
                                return;
                            }
                            ivSuccess.setVisibility(View.VISIBLE);
                            resultFile(fileId, item);
                        }
                    });
    }

    private void resultFile(String fileId, ChatTableBean item) {
        cpFileProgress.hide();
        if (!TextUtils.isEmpty(fileId) && Long.parseLong(fileId) > 0) {
            tvDownload.setVisibility(View.GONE);
            this.fileId = fileId;
            AlbumTableBean f = AlbumTableBean.queryById(Long.valueOf(fileId));
            if (f != null && !TextUtils.isEmpty(f.getMPath())) {
                tvLocPath.setText(f.getMPath());
                item.setAlbumId(fileId);
                ChatTableBean.update(item);
//                getToolbarRightIv().setVisibility(View.VISIBLE);
//                getToolbarRightIv().setImageResource(R.mipmap.icon_elli);
//                getToolbarRightIv().setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View vv) {
//                        Intent intent = AndroidFileUtil.openFile(f.getMPath());
//                        if (intent != null) {
//                            startActivity(intent);
//                        }
//                    }
//                });
                setItemClick(f.getMPath(), this);
            }

        }
    }


    private String getFileName(String path, String suffix) {
        if (TextUtils.isEmpty(path)) {
            return null;
        }
        if (path.contains(suffix)) {
            String name = path.substring(path.lastIndexOf(suffix) + 1, path.length());
            if (name.contains(".")) {
                String endxx = name.substring(name.lastIndexOf("."), name.length());
                String stxx = name.substring(0, name.lastIndexOf("."));
                if (stxx.length() > 12) {
                    stxx = stxx.substring(0, 12) + "..";
                }
                return stxx + endxx;
            }
            return path.substring(path.lastIndexOf("/") + 1, path.length());
        }
        return path;
    }

    public String getFileSize(Long length) {
        DecimalFormat df = new DecimalFormat("0.00");//设置保留位数
        if (length >= 1048576) {
            return df.format((double) length / 1048576) + "MB";
        } else if (length >= 1024) {
            return df.format((double) length / 1024) + "KB";
        } else if (length < 1024) {
            return df.format((double) length) + "B";
        } else {
            return "0B";
        }
    }

    private int getMineTypeByUrl(String url) {
        if (TextUtils.isEmpty(url)) {
            return R.mipmap.icon_file_unknown;
        }
        String type = AndroidFileUtil.getMimeType(url);
        if (AndroidFileUtil.MimeType.DOC.equals(type) || AndroidFileUtil.MimeType.DOC.equals(type)) {
            return R.mipmap.icon_file_word;
        } else if (AndroidFileUtil.MimeType.XLS.equals(type) || AndroidFileUtil.MimeType.XLSX.equals(type)) {
            return R.mipmap.icon_file_excel;
        } else if (AndroidFileUtil.MimeType.PPT.equals(type) || AndroidFileUtil.MimeType.PPTX.equals(type)) {
            return R.mipmap.icon_file_ppt;
        } else if (AndroidFileUtil.MimeType.TEXT.equals(type)) {
            return R.mipmap.icon_file_txt;
        } else if (AndroidFileUtil.MimeType.APK.equals(type)) {
            return R.mipmap.icon_file_app;
        }

        return R.mipmap.icon_file_unknown;
    }

    @OnClick(R.id.tv_download)
    public void onViewClicked() {
        if (!TextUtils.isEmpty(fileId)) {

            return;
        }
        if (cpFileProgress.isShown()) {
            return;
        }
        if (msg != null) {
            cpFileProgress.show();
            showFile(msg);
        }

    }

    public void openBrowser(Context context, String url) {
        final Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        if (intent.resolveActivity(context.getPackageManager()) != null) {
//            final ComponentName componentName = intent.resolveActivity(context.getPackageManager());
            context.startActivity(Intent.createChooser(intent, "请选择浏览器"));
        } else {
            showToastSHORT("请下载浏览器");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AlbumManageUtil.getInstance().stopVoice();
    }
}
